package com.kye.express.business.jd.address_select;

import com.kye.base.Logger;
import com.kye.base.utils.GsonUtils;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.model.UserSession;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.address.AddressBean;
import com.kye.model.bean.address.request.RequestAddressCity;
import com.kye.model.bean.address.request.RequestAddressCountry;
import com.kye.model.bean.address.request.RequestAddressProvince;
import com.kye.model.bean.address.request.RequestAddressTown;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.AddressRemoteDatasource;
import com.kye.model.gson_adapter.ApiException;

import java.util.List;

import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 31/01/2018
 * @updated : 31/01/2018
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class AddressSelectFragmentConstract {

    interface AddressFragmentView extends IView {

        void onUser(User user);

        void getAddressListSuccess(List<AddressBean> addressBeans);

        void getAddressListServerFailed(String msg);

        void getAddressListNetFailed(String message);

        void onLoading();

        void onLoaded();

        void checkAddressAvailableSuccess(List<AddressBean> addressBeans);

        void checkAddressUnavailable(String message);

        void checkAddressTownAvailableFailed(String message);
    }

    public static class AddressFragmentPresenter extends BasePresenter<AddressSelectFragmentConstract.AddressFragmentView> {

        private AddressRemoteDatasource addressRemoteDatasource;

        public AddressFragmentPresenter() {
            addressRemoteDatasource = new AddressRemoteDatasource();
        }

        @Override
        public void bind(AddressFragmentView view) {
            super.bind(view);
            UserSession.getInstance()
                    .getUserForRx()
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }



        /**
         * 获取当前层级的地址列表
         * @param addressSelectLevel
         * @param id
         */
        public void getAddressList(AddressSelectLevel addressSelectLevel, int id) {
            Single.just(addressSelectLevel)
                    .flatMap(new Function<AddressSelectLevel, SingleSource<List<AddressBean>>>() {
                        @Override
                        public SingleSource<List<AddressBean>> apply(AddressSelectLevel addressSelectLevel) throws Exception {
                            switch (addressSelectLevel) {
                                case ADDRESS_LEVEL_1_PROVINCE:
                                    RequestAddressProvince requestAddressProvince = new RequestAddressProvince();
//                                    requestAddressProvince.setProvinceId(String.valueOf(id));
                                    return addressRemoteDatasource.getProvince(requestAddressProvince);
                                case ADDRESS_LEVEL_2_CITY:
                                    RequestAddressCity requestAddressCity = new RequestAddressCity();
                                    requestAddressCity.setCityId(String.valueOf(id));
                                    return addressRemoteDatasource.getCity(requestAddressCity);
                                case ADDRESS_LEVEL_3_COUNTRY:
                                    RequestAddressCountry requestAddressCountry = new RequestAddressCountry();
                                    requestAddressCountry.setCountyId(String.valueOf(id));
                                    return addressRemoteDatasource.getCountry(requestAddressCountry);
                                default:
                                    RequestAddressTown requestAddressTown = new RequestAddressTown();
                                    requestAddressTown.setTownId(String.valueOf(id));
                                    return addressRemoteDatasource.getTown(requestAddressTown);
                            }
                        }
                    })
                    .subscribeOn(Schedulers.io())
//                    .doOnSuccess(new Consumer<List<AddressBean>>() {
//                        @Override
//                        public void accept(List<AddressBean> addressBeans) throws Exception {
//                            ChineseCharToEn charToEn = ChineseCharToEn.getInstance();
//                            for (AddressBean address :
//                                    addressBeans) {
//                                address.setFirstLetter(charToEn.getFirstLetter(address.getName().substring(0, 1)).charAt(0));
//                            }
//                        }
//                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<List<AddressBean>>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onSuccess(List<AddressBean> addressBeans) {
                            Logger.d("onSuccess : \n" + GsonUtils.toJsonString(addressBeans, true));
                            getView().getAddressListSuccess(addressBeans);
                        }

                        @Override
                        public void onError(Throwable e) {
                            if (e instanceof ApiException) {
                                ApiException exception = (ApiException) e;
                                getView().getAddressListServerFailed(exception.getOpenApiResult().getMsg());
                            } else {
                                getView().getAddressListNetFailed(e.getMessage());
                            }
                        }
                    });
        }

        public void checkAddressTownAvailable(AddressSelectLevel addressSelectLevel, int id) {
            Single.just(addressSelectLevel)
                    .flatMap(new Function<AddressSelectLevel, SingleSource<List<AddressBean>>>() {
                        @Override
                        public SingleSource<List<AddressBean>> apply(AddressSelectLevel addressSelectLevel) throws Exception {
                            switch (addressSelectLevel) {
                                case ADDRESS_LEVEL_1_PROVINCE:
                                    RequestAddressCity requestAddressCity = new RequestAddressCity();
                                    requestAddressCity.setCityId(String.valueOf(id));
                                    return addressRemoteDatasource.getCity(requestAddressCity);
                                case ADDRESS_LEVEL_2_CITY:
                                    RequestAddressCountry requestAddressCountry = new RequestAddressCountry();
                                    requestAddressCountry.setCountyId(String.valueOf(id));
                                    return addressRemoteDatasource.getCountry(requestAddressCountry);
                                case ADDRESS_LEVEL_3_COUNTRY:
                                    RequestAddressTown requestAddressTown = new RequestAddressTown();
                                    requestAddressTown.setTownId(String.valueOf(id));
                                    return addressRemoteDatasource.getTown(requestAddressTown);
                                default:
                                    RequestAddressTown requestAddressTown2 = new RequestAddressTown();
                                    requestAddressTown2.setTownId(String.valueOf(id));
                                    return addressRemoteDatasource.getTown(requestAddressTown2);
                            }
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SingleObserver<List<AddressBean>>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(List<AddressBean> addressBeans) {
                            getView().onLoaded();
                            getView().checkAddressAvailableSuccess(addressBeans);
                        }

                        @Override
                        public void onError(Throwable e) {
                            getView().onLoaded();
                            if (e instanceof ApiException) {
                                ApiException apiException = (ApiException) e;
                                OpenApiResult openApiResult = apiException.getOpenApiResult();
//                                0	操作成功
//                                30000	操作失败
//                                30026	值不能为空
                                switch (openApiResult.getCode()) {
                                    case 30000:
                                    case 30026:
                                        getView().checkAddressUnavailable(e.getMessage());
                                        break;
                                }
                            } else {
                                getView().checkAddressTownAvailableFailed(e.getMessage());
                            }
                        }
                    });
        }
    }
}
